package cn.com.xy.sms.sdk.provider;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.NumberInfo;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.number.NumberLogoUtil;
import cn.com.xy.sms.sdk.number.ParseNumberUtil;
import cn.com.xy.sms.sdk.util.StringUtils;
/*SDK-637 zhaojiangwei 20160929 start*/
/**
 * 陌生来电信息提供者
 *
 * @author huangzhiqiang
 *
 */
public class StrangerCallsInfoProvider extends ContentProvider {

    private static final UriMatcher MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    
//    private static final String IMME_TYPE_PNG = "image/png";
    private static final String AUTHORITY = "cn.com.xy.sms.sdk.provider.strangercall";
    private static final String PATH_INFO = "numberInfo";
    private static final String PATH_IMG = "imgFile";
    private static final String PATH_INFO_NET = "netNumberInfo";
    private static final String PATH_IMG_NET = "netImgFile";
    
    /*IMOO-20 zhaojiangwei 20161221 start */
    private static final String PATH_INFO_T9 = "hotNumbers";
    /*IMOO-20 zhaojiangwei 20161221 end */

    private static final int URL_RES_INFO = 1;
    private static final int URL_RES_INFO_NET = 2;
    /*IMOO-20 zhaojiangwei 20161221 start */
    private static final int URL_RES_INFO_T9 = 3;
    /*IMOO-20 zhaojiangwei 20161221 end */
    
    static {
        MATCHER.addURI(AUTHORITY, PATH_INFO, URL_RES_INFO);
        MATCHER.addURI(AUTHORITY, PATH_INFO_NET, URL_RES_INFO_NET);
        /*IMOO-20 zhaojiangwei 20161221 start */
        MATCHER.addURI(AUTHORITY, PATH_INFO_T9, URL_RES_INFO_T9);
        /*IMOO-20 zhaojiangwei 20161221 end */
    }

    @Override
    public boolean onCreate() {
        return true;
    }

    private static boolean isLocalLogoExist(String logoName) {
    	if (StringUtils.isNull(logoName)) {
    		return false;
    	}
    	
    	File file = new File(Constant.getPath(Constant.DUOQU_PUBLIC_LOGO_DIR) + logoName);
    	if (file.exists()) {
    		return true;
    	}
      
    	return false;
    }
    
    /*IMOO-20 zhaojiangwei 20161221 start */
    private Cursor convertDataToCursor(String num, Uri uri, JSONObject jsObjData) throws Exception{
        if (jsObjData != null) {
            String[] curProjection = new String[] { "num", "result" };
            MatrixCursor cursor = new MatrixCursor(curProjection);
            Object[] row = new Object[curProjection.length];
            row[0] = num;
            jsObjData.put(NumberInfo.LOCAL_LOGO_KEY, isLocalLogoExist(jsObjData.optString(NumberInfo.LOGO_KEY)));
            row[1] = jsObjData.toString();
            cursor.addRow(row);
            cursor.setNotificationUri(getContext().getContentResolver(), uri);
            return cursor;
        }
        return null;
    }
    /*IMOO-20 zhaojiangwei 20161221 end */
  
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        JSONObject jsObjData = null;
        try {
            String num = null;
            int code = MATCHER.match(uri);
            switch (code) {
            case URL_RES_INFO:
                if (selectionArgs != null && selectionArgs.length > 0) {
                    num = selectionArgs[0];
                    jsObjData = ParseNumberUtil.queryByNum(num, null);
                    return convertDataToCursor(num, uri, jsObjData);
                }
                break;
            case URL_RES_INFO_NET:
                if (selectionArgs != null && selectionArgs.length > 0) {
                    num = selectionArgs[0];
                    jsObjData = ParseNumberUtil.queryByNet(num, null);
                    return convertDataToCursor(num, uri, jsObjData);
                }
                break;
            case URL_RES_INFO_T9:
                return ParseNumberUtil.queryAllT9Numbers();
            default:
                break;
            }
        }
        catch (Throwable e) {
            LogManager.e(Constant.TAG, "StrangerCallsInfoProvider query error:", e);
        }
        return null;
    }

    @Override
    public String getType(Uri uri) {
//        if (uri.toString().toLowerCase().endsWith(".png")) {
//            return IMME_TYPE_PNG;
//        }
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
       return null;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return 0;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return 0;
    }
    
    
    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
        List<String> paths = uri.getPathSegments();
        if (paths == null || paths.size() < 2) {
            throw new FileNotFoundException(uri.getPath());
        }
        String type = paths.get(0);
        String num = paths.get(1);
        File logFile = null;
        if (PATH_IMG.equals(type)) {
            logFile = NumberLogoUtil.findLogoFile(getContext(), num, null);
        }
        else if (PATH_IMG_NET.equals(type)) {
            Map<String, String> extend = new HashMap<String, String>();
            extend.put(NumberLogoUtil.DOWNLOAD_IN_THREAD_POOL, Boolean.FALSE.toString());
            logFile = NumberLogoUtil.findLogoFileByNet(getContext(), num, extend);
        }
        if (logFile != null && logFile.exists()) {
            return ParcelFileDescriptor.open(logFile, ParcelFileDescriptor.MODE_READ_ONLY);
        }
        throw new FileNotFoundException(uri.getPath());
//        if (isValidImgUri(uri)) {
//            List<String> paths = uri.getPathSegments();
//            if (paths!=null && paths.size()>0) {
//                int pathCount = paths.size();
//                String logoName = paths.get(pathCount-1);
//                String filePath = Constant.getPath(Constant.DUOQU_PUBLIC_LOGO_DIR)+logoName;
//                //LogManager.e("immo","file:"+filePath);
//                File file = new File(filePath);
//                if (file.exists()) {
//                    return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
//                }
//                else {
//                   //LogManager.e("immo", "file != exist");
//                }
//            }   
//        }
//        else{
//            //LogManager.e("immo", "uri error.....");
//        }
//        throw new FileNotFoundException(uri.getPath());
    }
    
//    private boolean isValidImgUri(Uri uri){
//        boolean opRet = false;
//        String uriStr = uri.toString();
//        if (uriStr.contains(AUTHORITY+"/"+PATH_IMG)) {
//            if (IMME_TYPE_PNG.equals(getType(uri))) {
//                opRet = true;
//            }
//        }
//        return opRet;
//    }
}
/*SDK-637 zhaojiangwei 20160929 end*/